<!--
import { useFileTransStore } from '@/stores/fileTransStore'; // 使用 Pinia Store
import type { MindElixirData } from 'mind-elixir';
import MindElixir from 'mind-elixir';
import { computed, onMounted } from 'vue';
 * @FilePath: \ilink-vue-frontend\src\views\Square\LearningSquare\Lesson\video\components\MindMap.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script lang="ts" setup>
import { useFileTransStore } from '@/stores/fileTransStore'; // 使用 Pinia Store
// import type { MindElixirData } from 'mind-elixir';
// import MindElixir from 'mind-elixir';
import { storeToRefs } from 'pinia';
import { computed, onMounted, ref } from 'vue';
import { Position, VueFlow } from "@vue-flow/core";
import { Background } from "@vue-flow/background";

// 从 Pinia Store 中获取 summarization 数据
const fileTransStore = useFileTransStore();
const { summarization } = storeToRefs(fileTransStore);

// 计算 MindMapSummary 的第一个项
const mindMapSummary = computed(() => summarization.value?.MindMapSummary?.[0]);

// 将节点转换为 MindElixirData 格式
const convertToMindElixirData = (node: any): any => {
  if (!node || !node.Title)
    return null;
  return {
    topic: node.Title,
    children: node.Topic?.map(convertToMindElixirData).filter(Boolean) || [],
  };
};

// 定义 VueFlow 节点的接口
interface VueFlowNode {
  id: string;
  type: string;
  position: { x: number; y: number };
  data: { label: string; labelNoId?: string };
  sourcePosition?: Position;
  targetPosition?: Position;
  style?: { backgroundColor: string; fontWeight: string; fontSize: string };
}

// 定义 VueFlow 边的接口
interface VueFlowEdge {
  id: string;
  source: string;
  target: string;
  sourceHandle?: string;
  targetHandle?: string;
  animated?: boolean;
  style?: { stroke: string; strokeWidth: number };
}

// 初始化 VueFlow 的 nodes 为一个空数组，为后续从jsonContent中解析数据做准备
const nodes = ref<VueFlowNode[]>([]);

// 初始化 VueFlow 的 edges 为一个空数组，为后续从jsonContent中解析数据做准备
const edges = ref<VueFlowEdge[]>([]);

onMounted(() => {
  // 判断是否为整数
  const isInteger = (str: string): boolean => {
    const num = parseInt(str, 10);
    return Number.isInteger(num) && num.toString() === str;
  };

  if (!mindMapSummary.value)
    return; // 如果没有数据，直接返回

  // 深度优先遍历脑图数据并打印
  const dfs = (node: any, parentId: string, curId: string) => {
    if (!node)
      return;

    // console.log(node);
    // 将节点转换为 VueFlow 的节点
    const vueFlowNode: VueFlowNode = {
      id: parentId + curId,
      type: 'default',
      position: { x: 0, y: 0 },
      data: { label: node.Title },
    };
    nodes.value.push(vueFlowNode);

    // dfs 遍历子节点
    if (node.Topic) {
      for (let i = 0; i < node.Topic.length; i++) {
        const child = node.Topic[i];
        dfs(child, parentId + curId, `.${(i + 1).toString()}`);
      }
    }
  };
  dfs(mindMapSummary.value, '', 'root');

  // 遍历 VueFlow 的 nodes，处理id和位置
  for (let i = 0; i < nodes.value.length; i++) {
    const node = nodes.value[i];

    // 1、处理id
    // 如果是根节点
    if (node.id === 'root') {
      node.position = { x: 0, y: 0 };
    }
    else {
      // 把id前面的root.去掉
      node.id = node.id.replace('root.', '');
    }

    // 2、处理位置
    // 通过.将id分割为数组，据此确定X轴位置
    const idArray = node.id.split('.');
    const curX = (idArray.length - 1) * 150;
    const previousY = i > 0 ? nodes.value[i - 1].position.y : 0;
    node.position = { x: curX, y: previousY + 100 };

    // 3、处理Position
    if (isInteger(node.id) || node.id === 'root') {
      node.sourcePosition = Position.Bottom;
      node.targetPosition = Position.Top;
      node.style = { backgroundColor: "orange", fontWeight: "bold", fontSize: "15px" };
    }
    else {
      node.sourcePosition = Position.Bottom;
      node.targetPosition = Position.Left;
      node.style = { backgroundColor: "lightblue", fontWeight: "bold", fontSize: "12px" };
    }

    // 4、生成edges
    if (node.id !== 'root') {
      if (isInteger(node.id)) {
        // 一级节点
        // 父节点为id小1的节点
        const parentId = parseInt(node.id, 10) - 1;
        edges.value.push({
          id: `edge-${node.id}`,
          source: parentId.toString(),
          target: node.id,
          animated: true,
          style: { stroke: 'orange', strokeWidth: 4 },
        });
      }
      else {
        // 非一级节点
        // 父节点为id去掉最后一个.的节点
        const parentId = node.id.substring(0, node.id.lastIndexOf('.'));
        edges.value.push({
          id: `edge-${node.id}`,
          source: parentId,
          target: node.id,
          animated: true,
          style: { stroke: 'lightblue', strokeWidth: 2 },
        });
      }
    }

    // 5、重新设置label，在前面加上id
    node.data.labelNoId = node.data.label;
    node.data.label = `${node.id} ${node.data.label}`;
    if (node.id === 'root') {
      // 替换label开始的root
      node.data.label = node.data.label.replace('root ', '');
    }
  }

  // 再补充一个root-1的边
  edges.value.push({
    id: 'edge-root-1',
    source: 'root',
    target: '1',
    animated: true,
    style: { stroke: 'orange', strokeWidth: 4 },
  });

  // 打印 VueFlow 的 nodes
  // console.log(nodes.value);
});
</script>

<template>
  <!-- <div id="map" style="width: 100%; height: 750px;" /> -->
  <!-- <VueFlow :nodes="nodes" :edges="edges" style="height: 90vh; width: 100%; color: red;" @node-click="onNodeClickFlow"> -->
  <VueFlow :nodes="nodes" :edges="edges" style="height: 90vh; width: 100%; color: red;">
    <Background pattern-color="#666" :gap="16" />
  </VueFlow>
</template>

<style>
/* 样式可以根据需要自定义 */
@import "@vue-flow/core/dist/style.css";
@import "@vue-flow/core/dist/theme-default.css";
/* 参考博客：https://blog.csdn.net/RenGJ010617/article/details/140619433 */
/* 官方examples：https://vueflow.dev/examples/ */
</style>
